<template>
    <el-dialog title="导入数据表" v-model="visible" width="600px">

        <el-form-item label="类型" prop="dbname">

            <el-select @change="handleOption" v-model="dbname" size="small">
                <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item" />
            </el-select>

        </el-form-item>

        <el-table :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" :stripe="stripe"
            tooltip-effect="dark" ref="multipleTable" style="width: 100%">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="tabname" label="表名称">
            </el-table-column>
            <el-table-column prop="comment" label="备注">
            </el-table-column>

        </el-table>

        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 15, 20]"
            :page-size="pagesize" layout="  prev, pager, next" :total="total">
        </el-pagination>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="visible = false">取 消</el-button>

                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts">
    import {
        onMounted,
        onUnmounted
    } from 'vue'
    const {
        Sequelize
    } = window.require('sequelize-typescript');
    import * as db_context from '@/models/db_context'
    import {
        ElMessage,
        ElTable
    } from 'element-plus'
    import {
        reactive,
        ref,
        toRefs
    } from 'vue'
import { stat } from 'original-fs';
  import commonAction from '@/utils/common'
    export default {
        name: 'DialogAddDb',
        props: {
            type: String, // 用于判断是添加还是编辑
            reload: Function // 添加或修改完后，刷新列表页
        },
        setup(props: any) {
            const formRef = ref < any > (null)
            const multipleTable = ref(null)
            const state = reactive({
                visible: false,

                stripe: true, //是否为斑马纹 table
                tableData: [],
                currentPage: 1,
                pagesize: 10,
                total: 0,
                dbname: "",
                options: [],
                db:{}

            })

            onMounted(() => {
                getDBs()
            })

            const handleSizeChange = (val: number) => {
                state.pagesize = val;
            }
            const handleCurrentChange = (val: number) => {
                state.currentPage = val;
            }
            // 开启弹窗
            const open = () => {
                state.visible = true

            }
            // 触发过滤项方法
            const handleOption = (val: db_context.GenDb) => {

                state.tableData=[];
                const sequelize = new Sequelize(val.dbName, val.dbUser, val.dbPass, {
                    host: val.host,
                    port: val.port,
                    dialect: val.type,
                    pool: {
                        max: 5,
                        min: 0,
                        idle: 10000
                    },
                    timezone: '+08:00'
                });

                sequelize.authenticate().then(() => {
                        //
                        var sql =
                            "select relname as tabname,cast(obj_description(relfilenode,'pg_class') as varchar) as comment from pg_class c where relname in (select tablename from pg_tables where schemaname='public' and position('_2' in tablename)=0)";

                         //mysql
                        if(val.type=='mysql'){
                            sql="select table_name as tabname, table_comment as comment from information_schema.tables	where table_schema = (select database())";
                        }
                        sequelize.query(sql, {
                            type: sequelize.QueryTypes.SELECT
                        }).then((resultDT: any) => {
                            state.tableData = resultDT;
                            state.total = resultDT.length;
                            //console.log('result:',resultDT)
                        });

                        state.db=val;


                    })
                    .catch(() => {
                        ElMessage.error('连接不上数据库')

                    });

            }

            // 关闭弹窗
            const close = () => {
                state.visible = false
            }
            const submitForm = async () => {
                //获取选中表格
                var bb: any = multipleTable.value;
                var tblist = bb.store.states.selection._rawValue;
                if (tblist.length <= 0) {
                    ElMessage.error('请选择表格')
                    return;
                }
                //获取配置信息
                await db_context.Project.getById < db_context.Project > (1).then((project: db_context.Project) => {

                        //遍历表格
                        tblist.forEach(async (element: any) => {
                            console.log(element);
                            var item: any = {
                                tableName: element.tabname,
                                tableComment: element.comment,
                                className: toHump(element.tabname),
                                tplCategory: "crud",
                                packageName: project.packageName,
                                moduleName: "system",
                                businessName: toHump(element.tabname),
                                functionName: element.comment,
                                functionAuthor: project.author


                            }

                             const dt = await db_context.GenTable.createItem < db_context.GenTable > (item);
                             console.log(dt);


                         
                          //获取表字段信息

                          //table 导入
                          const val:any=state.db;

                           var sqlTable="SELECT a.attnum, a.attname AS field, t.typname AS type, a.attlen AS length, a.atttypmod AS lengthvar, a.attnotnull AS notnull, b.description AS comment FROM pg_class c, pg_attribute a  LEFT JOIN pg_description b  ON a.attrelid = b.objoid  AND a.attnum = b.objsubid, pg_type t "
                          +"WHERE c.relname = '"+element.tabname+"'    AND a.attnum > 0    AND a.attrelid = c.oid    AND a.atttypid = t.oid ORDER BY a.attnum";


                          if(val.type=="mysql"){
                              sqlTable="select ordinal_position as attnum,COLUMN_NAME AS field, column_type AS type,column_comment as comment,is_nullable as notnull,(case when (is_nullable = 'no'  && column_key != 'PRI') then '1' else null end) as is_required	,(case when column_key = 'PRI' then '1' else '0' end) as is_pk "
                             +"from information_schema.columns where table_schema = (select database()) and table_name ='"+element.tabname+"'	order by ordinal_position";
                          }


                         const sequelize = new Sequelize(val.dbName, val.dbUser, val.dbPass, {
                            host: val.host,
                            port: val.port,
                            dialect: val.type,
                            pool: {
                             max: 5,
                             min: 0,
                             idle: 10000
                           },
                          timezone: '+08:00'
                          });

                 
                        //查询列，添加列**********************************
                         const dtables = await sequelize.query(sqlTable, {type: sequelize.QueryTypes.SELECT});
                         console.log(dtables);
                         dtables.forEach(async (t:any) => {
                              var item: any = {};
                              item.tableId=dt.id;
                              item.columnName=t.field;
                              item.columnComment=t.comment;
                              item.columnType=t.type;
                              item.javaType="";
                              item.javaField="";
                              item.isPk=t.is_pk;
                              item.isIncrement="";
                              item.isRequired="";
                              item.isInsert="1";
                              item.isEdit="1";
                              item.isList="1";
                              item.isQuery="";
                              item.queryType="";
                              item.htmlType="";
                              item.dictType="";
                              item.sort=t.attnum;
                              await db_context.GenTableColumn.createItem < db_context.GenTableColumn > (item);
                            
                           
                         });

                        
                        await commonAction.resetTables(element.tabname);
                         


                          //end*********************************************************







                        });
                        ElMessage.success('导入成功');
                          props.reload();


                    });



            }
            const getPgTables = () => {
                console.log('1111111111');

            }
            const getDBs = () => {
                db_context.GenDb.getList < db_context.GenDb > ().then((results: any) => {
                    console.log(results);
                    state.options = results;
                });

            }

            // 下划线转换驼峰
            const toHump = ((str: string): string => {
               var arr = str.split('_');
                return arr.map(function (item, index) {
                    if (index === 0) {
                        return item;
                    } else {
                        return item.charAt(0).toUpperCase() + item.slice(1);
                    }
                }).join('');
            })

            return {
                ...toRefs(state),
                open,
                close,
                handleOption,
                submitForm,
                handleSizeChange,
                handleCurrentChange,
                multipleTable
            }
        }
    }
</script>